using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class VNController:MonoBehaviour {

	public delegate void DialougeFinishCallback();
	DialougeFinishCallback onFinish;

	public static VNController instance;

	public GameObject rootObject;
	public Image portrait;
	public Text text;

	public bool debug;

	bool justLoaded;

	DialougeClip currentDialouge;
	int currentSentence;

	private void Awake() {
		instance=this;
	}
	private void OnDestroy() {
		instance=null;
	}

	private void LateUpdate() {
		if(justLoaded) {
			justLoaded=false;
			return;
		}
		if(currentDialouge==null) return;
		if(Input.GetKeyDown(KeyCode.Space)||(debug&&Application.isEditor)) {
			currentSentence++;
			if(currentSentence>=currentDialouge.content.Length) {
				ClearDisplay();
				onFinish?.Invoke();
				currentDialouge=null;
			} else {
				UseSentence(currentDialouge.content[currentSentence]);
			}
		}
	}

	public void EnterDialouge(DialougeClip dialouge,DialougeFinishCallback callback = null) {
		if(!dialouge||dialouge.content.Length==0) {
			callback?.Invoke();
			return;
		}
		currentDialouge=dialouge;
		currentSentence=0;
		onFinish=callback;
		UseSentence(currentDialouge.content[0]);
	}

	void ClearDisplay() {
		rootObject.SetActive(false);
	}
	void UseSentence(DialougeSentence sentence) {
		if(sentence==null) {
			ClearDisplay();
			return;
		}
		rootObject.SetActive(true);
		if(sentence.sprite!=null) portrait.sprite=sentence.sprite;
		text.text=sentence.text;
		justLoaded=true;
	}

}
